package com.my.study.config;

import com.my.study.filter.XssFilter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.DispatcherType;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: yidujun
 * @create: 2021/04/16 14:40
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Value("${xss.enabled}")
    private String enabled;

    @Value("${xss.excludes}")
    private String excludes;

    @Value("${xss.urlPatterns}")
    private String urlPatterns;


    @SuppressWarnings({"rawtypes", "unchecked"})
//    @Bean
//    public FilterRegistrationBean xssFilterRegistration() {
//        FilterRegistrationBean registration = new FilterRegistrationBean();
//        registration.setDispatcherTypes(DispatcherType.REQUEST);
//        registration.setFilter(new XssFilter());
//        registration.addUrlPatterns(urlPatterns.split(","));
//        registration.setName("xssFilter");
//        registration.setOrder(FilterRegistrationBean.HIGHEST_PRECEDENCE);
//        Map<String, String> initParameters = new HashMap<>(2);
//        initParameters.put("excludes", excludes);
//        initParameters.put("enabled", enabled);
//        registration.setInitParameters(initParameters);
//        return registration;
//    }


    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new CustomInterceptor())
                .addPathPatterns("/get/**")
                .excludePathPatterns("/**");

        registry.addInterceptor(new Custom1Interceptor())
                .addPathPatterns("/get1/**")
                .excludePathPatterns("/**");
    }



    public static class CustomInterceptor extends HandlerInterceptorAdapter {
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            return super.preHandle(request, response, handler);
        }
    }

    public static class Custom1Interceptor extends HandlerInterceptorAdapter {
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            return super.preHandle(request, response, handler);
        }
    }
}
